<?php

/**
 * Description of Link
 *
 * @author user3
 */
class Ga_Db_Link {

    const LINK_SEPARATOR = "::";

    /**
     *
     * @var Bluembo_Db_Rowset 
     */
    protected $_parentRowset;

    /**
     *
     * @var Bluembo_Db_Rowset
     */
    protected $_dependentRowset;

    /**
     *
     * @var array 
     */
    protected $_dependentMap;

    /**
     *
     * @var array 
     */
    protected $_parentMap;
    protected $_key;

    function __construct(Bluembo_Db_Rowset $parentRowset, Bluembo_Db_Rowset $dependentRowset)
    {
        $this->_parentRowset = $parentRowset;
        $this->_dependentRowset = $dependentRowset;
        $this->_key = self::createKey($this->_parentRowset, $this->_dependentRowset);
    }

    public static function createKey($parent, $dependent)
    {
        $parentTable    = $parent instanceof Bluembo_Db_Rowset ? $parent->getTableClass() : $parent;
        $dependentTable = $dependent instanceof Bluembo_Db_Rowset ? $dependent->getTableClass() : $dependent;
        return $parentTable . self::LINK_SEPARATOR . $dependentTable;
    }

    public function getKey()
    {
        return $this->_key;
    }

    public function getParentRowset()
    {
        return $this->_parentRowset;
    }

    public function setParentRowset($_parentRowset)
    {
        $this->_parentRowset = $_parentRowset;
    }

    public function getDependentRowset()
    {
        return $this->_dependentRowset;
    }

    public function setDependentRowset($dependentRowset)
    {
        $this->_dependentRowset = $dependentRowset;
    }

    public function getDependentMap()
    {
        if (!$this->_dependentMap) {
            $fieldKey = $this->_getFieldKey('columns');
            $this->_dependentMap = $this->_dependentRowset->getMap($fieldKey);
        }
        return $this->_dependentMap;
    }

    public function getParentMap()
    {
        if (!$this->_parentMap) {
            $fieldKey = $this->_getFieldKey('refColumns');
            $this->_parentMap = $this->_parentRowset->getMap($fieldKey);
        }
        return $this->_parentMap;
    }

    private function _getFieldKey($type)
    {
        $dependentTable = $this->_dependentRowset->getTable();
        $parentTable    = $this->_parentRowset->getTable();
        $reference      = $dependentTable->getReference(get_class($parentTable));
        return $reference[$type][0];
    }

}